package megrez.bussiness.schedule.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;

import org.springframework.beans.BeanUtils;

import lombok.Getter;
import lombok.Setter;
import megrez.common.jpa.AbstractIdAuditingEntity;

/**
 * 任务
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@Entity
@Getter
@Setter
@Table(name = "job")
public class Job extends AbstractIdAuditingEntity {
    public static enum State {
        /** 启动 */
        STARTED,
        /** 异常 */
        ERROR,
        /** 停止 */
        STOPPED,
        /** 运行 */
        RUNNING;
    }
 
    /** bean名称 */
    @Column(nullable = false)
    private String className;
    
    /** 方法名称 */
    @Column(nullable = false)
    private String methodName;

    /** 方法参数 */
    private String methodParams;

    /** cron表达式 */
    @Column(nullable = false)
    private String cronExpression;

    /** 备注 */
    private String remark;

    /** 启用 */
    private Boolean enabled;

    /** 状态 */
    @Enumerated(EnumType.STRING)
    private State state;

    @OneToMany(mappedBy = "job", cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
    private List<JobLog> logs = new ArrayList<>();

    public Job() {
    }

    public Job(String className, String methodName, String cronExpression) {
        this.className = className;
        this.methodName = methodName;
        this.cronExpression = cronExpression;
    }

    public Job(String className, String methodName, String methodParams, String cronExpression, String remark) {
        this.className = className;
        this.methodName = methodName;
        this.methodParams = methodParams;
        this.cronExpression = cronExpression;
        this.remark = remark;
    }

    public void copy(Job source) {
        BeanUtils.copyProperties(source, this, "id,logs");
    }
    
    @PrePersist
    @PreUpdate
    public void preAction() {
        if (this.enabled == null) {
            this.enabled = true;
        }

        if (this.state == null) {
            this.state = State.STOPPED;
        }
    }
}
